package codeMaker;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;

import constant.ChildWindowConstant;
import constant.Filed_cn;
import constant.Filed_eng;
import constant.ServiceTypeComboBox;
import entity.MakeEntityModel;

public class MakeEntity {

	private JFrame frame;
	private JTextField entityName;
	private JTextField entityName_cn;

	public JFrame getFrame() {
		return frame;
	}

	public void setFrame(JFrame frame) {
		this.frame = frame;
	}

	/**
	 * Launch the application.
	 */
	public static void main() {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					MakeEntity window = new MakeEntity();
					ChildWindowConstant.makeEntity = window;
					window.frame.setVisible(true);

				} catch (Exception e) {

				}
			}
		});
	}

	/**
	 * test
	 * 
	 * @param parameters
	 */
	/*
	 * public static void main(String[] args) { EventQueue.invokeLater(new
	 * Runnable() { public void run() { try {
	 * 
	 * TablesQuery window = new TablesQuery(); ChildWindowConstant.tablesQuery =
	 * window; window.frame.setVisible(true);
	 * 
	 * } catch (Exception e) {
	 * 
	 * } } }); }
	 */

	/**
	 * Create the application.
	 */
	public MakeEntity() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setResizable(true);
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(MakeEntity.class
				.getResource("/org/pushingpixels/substance/internal/contrib/randelshofer/quaqua/images/pencil.png")));
		frame.setTitle("自定义实体");
		frame.setBounds(100, 100, 781, 530);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		JScrollPane queryScrollPane = new JScrollPane();

		JButton addField = new JButton("添加字段");

		JLabel label = new JLabel("英文名称");

		entityName = new JTextField();
		entityName.setColumns(10);

		JLabel lblbean = new JLabel("查看已配置的实体");

		JComboBox<String> entityListCombox = new JComboBox<String>();

		String[] modelArr = ChildWindowConstant.makeEntityEngAndCn.keySet().toArray(new String[] {});

		entityListCombox.setModel(new DefaultComboBoxModel<>(new String[] { "--请选择--" }));

		for (String model : modelArr) {
			entityListCombox.addItem(model);
		}

		JLabel cnLable = new JLabel("中文名称");

		entityName_cn = new JTextField();
		entityName_cn.setColumns(10);

		JLabel label_2 = new JLabel("*");
		label_2.setForeground(Color.RED);

		JButton confirmButton = new JButton("确定");

		JButton deleteButton = new JButton("删除");

		JButton deleteLastRow = new JButton("删除尾行");

		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.TRAILING).addGroup(groupLayout
				.createSequentialGroup().addGap(25)
				.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(entityListCombox, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblbean)
						.addGroup(groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING).addComponent(cnLable)
										.addComponent(label))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
										.addComponent(entityName_cn, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 106,
												Short.MAX_VALUE)
										.addComponent(entityName, Alignment.TRAILING))
								.addPreferredGap(ComponentPlacement.RELATED).addComponent(label_2)))
				.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup().addGap(13)
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addGroup(groupLayout.createSequentialGroup().addComponent(confirmButton)
												.addPreferredGap(ComponentPlacement.RELATED).addComponent(deleteButton))
										.addComponent(queryScrollPane, GroupLayout.PREFERRED_SIZE, 514,
												GroupLayout.PREFERRED_SIZE)))
						.addGroup(groupLayout.createSequentialGroup().addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(addField).addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(deleteLastRow)))
				.addGap(45)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup().addGap(31).addGroup(groupLayout
						.createParallelGroup(Alignment.TRAILING)
						.addGroup(groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label)
										.addComponent(entityName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE)
										.addComponent(label_2))
								.addGap(18))
						.addGroup(groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(addField)
										.addComponent(deleteLastRow))
								.addPreferredGap(ComponentPlacement.UNRELATED)))
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
								.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(cnLable)
										.addComponent(entityName_cn, GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addGap(18).addComponent(lblbean).addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(entityListCombox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE))
								.addComponent(queryScrollPane, GroupLayout.PREFERRED_SIZE, 286,
										GroupLayout.PREFERRED_SIZE))
						.addGap(18).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(confirmButton).addComponent(deleteButton))
						.addGap(323)));

		JPanel querysPanel = new JPanel();
		queryScrollPane.setViewportView(querysPanel);
		querysPanel.setLayout(new GridLayout(0, 3, 5, 5));

		String[] fieldArr = new String[] { "字段名称", "注释", "字段类型" };

		deleteLastRow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// 获取容器个数
				int componentCount = querysPanel.getComponentCount();

				if (componentCount == 0) {
					return;
				}
				// 一行有6个
				// 如果是12，全部移除
				if (componentCount == 6) {
					querysPanel.removeAll();
					// 否则，移除最后6个
				} else {
					querysPanel.remove(componentCount - 1);
					querysPanel.remove(componentCount - 2);
					querysPanel.remove(componentCount - 3);
				}

				frame.validate();
				frame.repaint();
			}
		});

		addField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (!canAddField(querysPanel)) {
					return;
				}

				if (querysPanel.getComponentCount() == 0) {
					for (String queryStr : fieldArr) {
						JLabel label = new JLabel(queryStr);
						querysPanel.add(label);
					}
					addFieldMethod(querysPanel);
				} else {
					addFieldMethod(querysPanel);
				}

				frame.validate();
				frame.repaint();
			}

			private boolean canAddField(JPanel querysPanel) {

				if (querysPanel.getComponentCount() >= 6) {

					Component[] components = querysPanel.getComponents();
					for (int i = 3; i < components.length; i++) {

						if ("Filed_eng".equals(components[i].getClass().getSimpleName())) {

							Filed_eng filed_eng = (Filed_eng) components[i];

							if ("".equals(filed_eng.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再添加字段！（字段名称不能为空）", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						}
					}
				}

				return true;
			}

			private void addFieldMethod(JPanel querysPanel) {

				// 字段
				JTextField tableFiled = new Filed_eng();

				// 中文名称
				JTextField tableFiled_cn = new Filed_cn();

				// 字段类型
				JComboBox<String> filedType = new ServiceTypeComboBox<>();

				String[] typeList = new String[] { "String", "Byte", "Short", "Integer", "Float", "Double", "Long",
						"Char", "Boolean", "List" };

				filedType.setModel(new DefaultComboBoxModel<String>(typeList));

				querysPanel.add(tableFiled);
				querysPanel.add(tableFiled_cn);
				querysPanel.add(filedType);
			}

		});

		// 配置模块下拉框监听
		entityListCombox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {

				if (e.getStateChange() != 1) {
					return;
				}

				// 选取的当前模块
				String currentEntityName = entityListCombox.getSelectedItem().toString();

				if ("--请选择--".equals(currentEntityName)) {

					entityName.setText("");
					entityName_cn.setText("");
					querysPanel.removeAll();

					frame.validate();
					frame.repaint();

					return;

				}

				entityName.setText(currentEntityName);

				String currentEntityName_cn = ChildWindowConstant.makeEntityEngAndCn.get(currentEntityName);

				entityName_cn.setText(currentEntityName_cn);

				List<MakeEntityModel> makeEntityModels = ChildWindowConstant.makeEntityModelMap.get(currentEntityName);

				// 移除panel的组件
				querysPanel.removeAll();

				// 加入表头和内容
				for (String tableStr : fieldArr) {
					JLabel label = new JLabel(tableStr);
					querysPanel.add(label);
				}

				for (MakeEntityModel entityModel : makeEntityModels) {

					JTextField filed_eng = new Filed_eng();
					filed_eng.setText(entityModel.getFiledName_eng());
					JTextField filed_cn = new Filed_cn();
					filed_cn.setText(entityModel.getFiledName_cn());
					// 字段类型
					JComboBox<String> filedType = new ServiceTypeComboBox<>();

					String[] typeList = new String[] { "String", "Byte", "Short", "Integer", "Float", "Double", "Long",
							"Char", "Boolean", "List" };

					filedType.setModel(new DefaultComboBoxModel<String>(typeList));
					filedType.setSelectedItem(entityModel.getServiceType());

					querysPanel.add(filed_eng);
					querysPanel.add(filed_cn);
					querysPanel.add(filedType);

				}

				frame.validate();
				frame.repaint();

			}

		});

		/**
		 * 确定设置实体
		 */
		confirmButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				String entityNameStr = entityName.getText();
				
				if ("".equals(entityNameStr)) {
					JOptionPane.showMessageDialog(frame, "实体名称不能为空！请填写！！", "错误",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				

				String entityNameStr_cn = entityName_cn.getText();

				entityNameStr_cn = "".equals(entityNameStr_cn) ? entityNameStr : entityNameStr_cn;
				
				if (ChildWindowConstant.makeEntityEngAndCn.containsKey(entityNameStr)) {

					int getCodeConfirmDialog = JOptionPane.showConfirmDialog(frame,
							"当前实体‘" + entityNameStr + "’已存在，确认覆盖？", "提示", JOptionPane.YES_NO_OPTION);

					if (getCodeConfirmDialog != 0) {
						return;
					}
				}

				// 内容
				Component[] queryComponents = querysPanel.getComponents();
				List<MakeEntityModel> makeEntityModels = new ArrayList<>();

				for (int i = 3; i < queryComponents.length; i++) {

					if ("Filed_eng".equals(queryComponents[i].getClass().getSimpleName())) {

						Filed_eng filed_eng = (Filed_eng) queryComponents[i];

						String engFiled = filed_eng.getText();

						if ("".equals(engFiled)) {
							JOptionPane.showMessageDialog(frame, "添加字段中的名称列不能为空！请填写！！", "错误",
									JOptionPane.ERROR_MESSAGE);
							return;
						}

						MakeEntityModel makeEntityModel = new MakeEntityModel();

						makeEntityModel.setFiledName_eng(engFiled);

						makeEntityModels.add(makeEntityModel);

					}

					else if ("Filed_cn".equals(queryComponents[i].getClass().getSimpleName())) {

						Filed_cn filed_cn = (Filed_cn) queryComponents[i];

						String filedName_eng = makeEntityModels.get(makeEntityModels.size() - 1).getFiledName_eng();

						String cnFiled = "".equals(filed_cn.getText()) ? filedName_eng : filed_cn.getText();

						makeEntityModels.get(makeEntityModels.size() - 1).setFiledName_cn(cnFiled);
					}

					else if ("ServiceTypeComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) queryComponents[i];

						String filedType = (String) serviceTypeComboBox.getSelectedItem();

						makeEntityModels.get(makeEntityModels.size() - 1).setServiceType(filedType);

					}

				}

				if (makeEntityModels.size() == 0) {
					JOptionPane.showMessageDialog(frame, "请配置实体的字段信息！", "错误", JOptionPane.ERROR_MESSAGE);
					return;
				}

				ChildWindowConstant.makeEntityEngAndCn.put(entityNameStr, entityNameStr_cn);
				ChildWindowConstant.makeEntityModelMap.put(entityNameStr, makeEntityModels);

				JOptionPane.showMessageDialog(frame, "当前实体配置成功！", "提示", JOptionPane.INFORMATION_MESSAGE);

				String[] entityNameArr = ChildWindowConstant.makeEntityModelMap.keySet().toArray(new String[] {});

				entityListCombox.setModel(new DefaultComboBoxModel<>(new String[] { "--请选择--" }));

				for (String entity : entityNameArr) {
					entityListCombox.addItem(entity);
				}

				entityListCombox.setSelectedItem(entityNameStr);
				entityName_cn.setText(entityNameStr_cn);

				frame.validate();
				frame.repaint();

			}
		});

		/**
		 * 删除当前实体
		 */
		deleteButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if ("".equals(entityName.getText())) {
					return;
				}

				int deleteFlg = JOptionPane.showConfirmDialog(frame, "确定删除当前实体‘" + entityName.getText() + "’吗？",
						"提示", JOptionPane.YES_NO_OPTION);

				if (deleteFlg != 0) {
					return;
				}
				
				ChildWindowConstant.makeEntityModelMap.remove(entityName.getText());
				
				ChildWindowConstant.makeEntityEngAndCn.remove(entityName.getText());
				
				
				String[] entityNameArr = ChildWindowConstant.makeEntityModelMap.keySet().toArray(new String[] {});

				entityListCombox.setModel(new DefaultComboBoxModel<>(new String[] { "--请选择--" }));

				for (String entity : entityNameArr) {
					entityListCombox.addItem(entity);
				}
				
				entityName.setText("");
				entityName_cn.setText("");
				
				querysPanel.removeAll();
				
				frame.validate();
				frame.repaint();
				
				JOptionPane.showMessageDialog(frame, "已删除！！", "提示",
						JOptionPane.INFORMATION_MESSAGE);
				

			}
		});

		frame.getContentPane().setLayout(groupLayout);
	}
}
